import { StyleSheet, Text, View } from 'react-native'
import React, { useContext, useState, useEffect } from 'react'
import { io } from 'socket.io-client'
import { setOnlineMsgAction } from '../redux/actionCreator/chat'
import store from '../redux/store'
import { setOfflineMsgAction } from '../redux/actionCreator/chat'

const SocketContext = React.createContext()

export const useSocket = () => {
  return useContext(SocketContext)
}

export const SocketProvider = ({ user, children
}) => {
  const [socket, setSocket] = useState()
  useEffect(() => {
    console.log('SocketProvider========================================')
    console.log('user', user)
    if (user.token) {
      const newSocket = io('wss://mini-cloud.top:3001', {
        auth: {
          token: user.token
        },
        // autoConnect: true,
        transports: ['websocket']
      })

      setSocket(newSocket)

      newSocket.on('connect', () => {
        console.log('app的ws 已连接', newSocket.id);

        // 根据id监听我的消息
        newSocket.on(user._id, (data) => {
          console.log('收到消息', data)
          store.dispatch(setOnlineMsgAction(data))
        });
        // 监听离线消息
        newSocket.on('offlineMsg', (list) => {
          // 收到服务器推送的消息，可以跟进自身业务进行操作
          console.log('离线消息消息：', list);
          store.dispatch(setOfflineMsgAction(list))
        });
        // 连接断开
        newSocket.on("disconnect", () => {
          console.log('连接断开了')
        });
      });

      newSocket.on('error', (msg) => {
        console.log('ws error', msg);
      });
    }
    return () => {
      socket?.off()
    }
  }, [user])
  return (
    <SocketContext.Provider value={socket}>
      {children}
    </SocketContext.Provider>
  )
}